//
//  AppDelegate.swift
//  WeiBo_One
//
//  Created by 李炎 on 15/10/19.
//  Copyright © 2015年 蜡笔小炎. All rights reserved.
//

import UIKit
import CoreData


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    // 版本号 Key
    let versionKey = "CFBundleShortVersionString"

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 程序入口控制器
        window?.rootViewController = startController()
        window?.makeKeyAndVisible()
        
        // 设置全局外观
        setupApearance()
        
//        /// 通知触发方法,切换跟控制器
//        func switchRootViewController(n: NSNotification) {
//            
//            let vc = n.object == nil ? MainTabbarController() : WelcomeViewController()
//            
//            window?.rootViewController = vc
//        }
//        
//        // 添加通知监听者1
//        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController", name: WBSwitchRootControllerNotification, object: nil)
        
        // 添加通知监听者2
        NSNotificationCenter.defaultCenter().addObserverForName(WBSwitchRootControllerNotification, object: nil, queue: nil) { (n) -> Void in
            
            let vc = n.object == nil ? MainTabbarController() : WelcomeViewController()
            
            self.window?.rootViewController = vc
        }
        
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WBSwitchRootControllerNotification, object: nil)
    }
 
    /// 检查当前是否是新版本
    private func isNewVersion() -> Bool {
        // 获取当前版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        // 取出沙盒中存储的Version
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        
        // 保存新版本
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: versionKey)
        
        // 返回是否是新版本
        return currentVersion > sandboxVersion
    }

    /// 返回启动根控制器
    private func startController() -> UIViewController {
        // 判断是否登录
        if UserAccountViewModel.sharedAccoutViewModel.userLogon {
            // 判断是否是新版本
            return isNewVersion() ? NewFutureCollectionViewController() : WelcomeViewController()
        }
        return MainTabbarController()
    }
}




//MARK: - 设置全局外观
extension AppDelegate {
    /// 设置全局外观
    func setupApearance() {
        UITabBar.appearance().tintColor = WeiBoAppearanceTintColor
        UINavigationBar.appearance().tintColor = WeiBoAppearanceTintColor
    }
}

